package com.solute.web.sso.login;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.solute.domain.LoginVO;
import com.solute.domain.ValidVO;
import com.solute.utils.regex.RegexConstants;
import com.solute.web.sessions.User;
import com.solute.web.sso.login.exceptions.LoginSubmitException;
import com.solute.web.sso.login.service.LoginService;

@Controller
@RequestMapping("/login")
@SessionAttributes({"user"})
public class LoginController {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	private static final String LOGIN_PASS_URL = "redirect:/main/index";
	
	private @Autowired LoginService loginService; 
	
	@RequestMapping(method=RequestMethod.GET)
	public ModelAndView main(HttpServletRequest request, ModelMap modelMap) {
		logger.info("login page prepare start");
		ModelAndView mav;
		boolean isLogined = (Boolean)request.getAttribute("isLogined");
		
		if(isLogined) {
			mav = new ModelAndView(LOGIN_PASS_URL);
		} else {
			User user = loginService.getUserFromIp(request.getRemoteAddr());
			if(user == null)
				mav = new ModelAndView("login");
			else {
				modelMap.addAttribute("user", user);
				mav = new ModelAndView(LOGIN_PASS_URL);
			}
		}
		logger.info("login page finished");
		
		return mav;
	}
	
	@RequestMapping(value="/validation", method=RequestMethod.POST)
	public @ResponseBody
	List<?> valid(@ModelAttribute LoginVO param, BindingResult result) {
		List<ValidVO> valids = new LinkedList<ValidVO>();
		
		if(!StringUtils.hasText(param.getEmail())) {
			valids.add(new ValidVO("email", "이메일을 입력해주십시오."));
		} else if(!param.getEmail().matches(RegexConstants.EMAIL_FORMAT)) {
			valids.add(new ValidVO("email", "이메일을 제대로 입력해주십시오."));
		}
		
		if(!StringUtils.hasText(param.getPassword())) {
			valids.add(new ValidVO("password", "비밀번호를 입력해주십시오."));
		}
			
		return valids;
	}
	
	@RequestMapping(value="/submit", method=RequestMethod.POST)
//	@RequestMapping(value="/submit")
	public @ResponseBody
	void submit(HttpServletRequest request, @ModelAttribute LoginVO param, BindingResult result, ModelMap modelMap) {
		if(result.hasErrors()) {
			logger.error("/login/submit Login Failed!");
			throw new RuntimeException();
		}
		
		if(!loginService.checkLogin(param)) {
			throw new LoginSubmitException();
		} else {
			User user = new User();
			user.setEmail(param.getEmail());
			modelMap.addAttribute("user", user);
			
			if(param.isSave()) {
				loginService.saveLogin(param, request.getRemoteAddr());
			}
		}
	}
	
}
